package com.cch.cooperation.api.common.sdk.umeng;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.cch.cooperation.api.common.sdk.umeng.util.SignUtil;
import com.cch.cooperation.common.exception.BizException;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class UmengClient {

    private String appKey;
    private String appSecret;
    private String umengAppKey;

    private static final String BASE_URL = "https://verify5.market.alicloudapi.com";

    public UmengClient(String umengAppKey, String appKey, String appSecret) {
        this.umengAppKey = umengAppKey;
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    public String getPhoneNumber(String token) {
        try {
            // 创建请求
            String apiPath = "/api/v1/mobile/info?appkey=" + umengAppKey;
            HttpRequest request = HttpRequest.post(BASE_URL + apiPath);
            // 设置请求体
            JSONObject body = new JSONObject(ImmutableMap.of("token", token));
            String contentMD5 = Base64.encode(MD5.create().digest(body.toString()));
            // 添加请求头
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("Content-Type", "application/json; charset=UTF-8");
            headers.put("Accept", "application/json");
            headers.put("X-Ca-Version", "1");
            headers.put("X-Ca-Signature-Headers", "X-Ca-Version,X-Ca-Stage,X-Ca-Key,X-Ca-Timestamp");
            headers.put("X-Ca-Stage", "RELEASE");
            headers.put("X-Ca-Key", appKey);
            headers.put("X-Ca-Timestamp", String.valueOf(System.currentTimeMillis()));
            headers.put("X-Ca-Nonce", UUID.randomUUID().toString());
            headers.put("Content-MD5", contentMD5);
            headers.put("X-Ca-Signature", SignUtil.generate(apiPath, "POST", headers, appSecret));
            headers.forEach(request::header);
            request.body(body.toJSONString());
            try (HttpResponse resp = request.execute()) {
                String json = resp.body();
                JSONObject respObj = JSONObject.parseObject(json);
                if (!Boolean.TRUE.equals(respObj.getBoolean("success"))) {
                    log.error("获取手机号失败, resp: {}", json);
                    throw new BizException("获取手机号失败, " + respObj.get("message"));
                }
                return respObj.getJSONObject("data").getString("mobile");
            }
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取手机号异常", e);
        }
        return null;
    }
}
